package com.java.thread;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadPoolTests {
    private static int corePoolSize=2;
    private static int maximumPoolSize=3;
    private static int keepAliveTime=60;
    private static BlockingQueue<Runnable> workQueue=
            new ArrayBlockingQueue<>(1);
    private static ThreadFactory threadFactory=new ThreadFactory() {
        private AtomicInteger atomicInteger=
                new AtomicInteger(1);
        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "service-tast-"+atomicInteger.getAndIncrement());
        }
    };
    public static void main(String[] args) {
        //1.创建线程池对象
        ThreadPoolExecutor poolExecutor=
                new ThreadPoolExecutor(corePoolSize,
                        maximumPoolSize,
                        keepAliveTime ,
                        TimeUnit.SECONDS,
                        workQueue,
                        threadFactory,
                        new ThreadPoolExecutor.CallerRunsPolicy());//拒绝策略
        //2.执行任务
        poolExecutor.execute(new Runnable() {
            @Override
            public void run() {
                String tThread=Thread.currentThread().getName();
                try{Thread.sleep(5000);}catch(Exception e){};
                System.out.println(tThread+"->task-01");
            }
        });
        poolExecutor.execute(new Runnable() {
            @Override
            public void run() {
                String tThread=Thread.currentThread().getName();
                try{Thread.sleep(5000);}catch(Exception e){};
                System.out.println(tThread+"->task-02");
            }
        });
        poolExecutor.execute(new Runnable() {
            @Override
            public void run() {
                String tThread=Thread.currentThread().getName();
                try{Thread.sleep(5000);}catch(Exception e){};
                System.out.println(tThread+"->task-03");
            }
        });
        poolExecutor.execute(new Runnable() {
            @Override
            public void run() {
                String tThread=Thread.currentThread().getName();
                //try{Thread.sleep(5000);}catch(Exception e){};
                System.out.println(tThread+"->task-04");
            }
        });
        poolExecutor.execute(new Runnable() {
            @Override
            public void run() {
                String tThread=Thread.currentThread().getName();
                //try{Thread.sleep(5000);}catch(Exception e){};
                System.out.println(tThread+"->task-05");
            }
        });
    }

}
